/*
* Author : Bingo
* */

var gulp          = require("gulp"),
    scss           = require("gulp-sass"), //编译scss
    browserSync    = require('browser-sync').create(), //gulp控制,自动刷新的服务器
    reload         = browserSync.reload,
    notify        = require('gulp-notify'),  //提示信息
    sourcemaps   = require('gulp-sourcemaps'), //为文件添加sourcemaps
    plumber        = require("gulp-plumber"),//发生错误时不停止任务
    runSequence  = require('run-sequence'), //使任务按序执行
    LessAutoprefix = require('less-plugin-autoprefix'),//为css添加私有前缀
    autoprefix     = new LessAutoprefix({ browsers: ['last 4 versions',"android >= 4", "ie >= 8"] }),
    jsonServer     = require('json-server');

var PATH = {
    appRoot : "./app/",
    scss : "./app/scss/",
    css : "./app/css/",
    reload:[ //这个目录和less目录下的内容变化时会刷新游览器
        /*"./app/views/!**!/!*.html",
        "./app/js/!**!/!*.js",
        "./app/router/!**!/!*.js",
        "./app/!*.js",
        "./app/config/!**!/!*.json",*/
    ],
}

//start browserSync server
gulp.task('browserSync',function(){
    browserSync.init({
        // proxy: "localhost:8001", //代理模式
        server: {baseDir: PATH.appRoot},//服务器模式
        port:"5580",
        ui: {
            port: 5581
        },
        //在Chrome浏览器中打开网站
        browser: "chrome"
    })
});


//编译less文件
gulp.task('scss',function(){
    console.log("scss编译中")
    return gulp.src(PATH.scss+ "theme.scss")
        .pipe(sourcemaps.init())
        .pipe(plumber({errorHandler: notify.onError('Error: <%= error.message %>')}))
        .pipe(scss({
            plugins: [autoprefix]
        }))
        .pipe(sourcemaps.write("."))
        .pipe(gulp.dest(PATH.css))
        .pipe(reload({stream:true}))
});


gulp.task('watch',function(){
    gulp.watch([PATH.scss + "**/*.scss"],['scss']); //监听less变化
    gulp.watch(PATH.appRoot + "**/*.html", browserSync.reload); //监听主目录文件夹下的html变化
    gulp.watch(PATH.reload,function () { //保存刷新
        reload()
    });
});

gulp.task('default',function(){
    runSequence(['browserSync','scss','watch']);        //默认的开发任务，编译css
});